﻿using System;
using DC2010.Effects;
using DC2010.Objects.Data;
using log4net;
using System.Reflection;

namespace DC2010.Systems
{
    public class EffectSystem : BaseSystem<EffectInfo, EffectGfx, EffectData>
    {
        public InstancesEffects Instances { get; set; }

        public override void Init(string code)
        {
            IsUsingInfo = true;
            IsUsingData = true;
			IsUsingGfx = false;
		
            InfoFileName = "Data\\" + code + "Info.xml";
            GfxFileName = "Data\\" + code + "Gfx.xml";
            DataFileName = "Temp\\" + code + "Data.xml";

            Code = code;

            DateTime dtStart = DateTime.Now;
            base.Init(code);

            //prepare effects for common use
            Instances = new InstancesEffects();


            log.Info("Core, Effects init takes: " + (DateTime.Now - dtStart).TotalSeconds + " seconds");
        }

        /// <summary>
        /// Method will create new instance of effect. Definition of this effect is in EffectData. EffectData 
        /// is passed as parametr to Effect.
        /// </summary>
        /// <param name="ed"></param>
        /// <returns></returns>
        public EffectLogic InstantiateEffect(EffectData ed)
        {
            //Effect are stored in "DC2010.Effects" namespace

            EffectInfo ei = GetInfo(ed.InfoId);
            string FullName = "DC2010.Effects." + ei.Method;

            try
            {
                Assembly assembly = Assembly.GetCallingAssembly();
                Type type = assembly.GetType(FullName);

                object o = Activator.CreateInstance(type, ed);

                if ((o != null) && (o is EffectLogic))
                {
                    //this is place where all intance are alive
                    AddData(ed);
                    return (EffectLogic)o;
                }
            }
            catch (Exception)
            {
                return null;
                //log
            }

            return null;
        }
    }
}
